package king.dominic.jlibrary.util;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import static android.content.ContentValues.TAG;

/**
 * Created by king on 2017/4/19.
 * FileUtils
 */
@SuppressWarnings("unused")
public class FileUtils {
    public static String PROVIDER_PATH_NAME = "dominic_king_external_path";

    private FileUtils() {
    }

    public static final int SIZE_TYPE_B = 1;//获取文件大小单位为B的double值
    public static final int SIZE_TYPE_KB = 2;//获取文件大小单位为KB的double值
    public static final int SIZE_TYPE_MB = 3;//获取文件大小单位为MB的double值
    public static final int SIZE_TYPE_GB = 4;//获取文件大小单位为GB的double值

    public static String fileHeader(String path) {
        if (path.startsWith("file:")) return path;
        return "file://" + path;
    }

    /**
     * 获取文件指定文件的指定单位的大小
     *
     * @param file     文件
     * @param sizeType 获取大小的类型1为B、2为KB、3为MB、4为GB
     * @return double值的大小
     */
    public static double getFileOrFilesSize(File file, int sizeType) {
        long blockSize = 0;
        try {
            if (file.isDirectory()) {
                blockSize = getFileSizes(file);
            } else {
                blockSize = getFileSize(file);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return FormatFileSize(blockSize, sizeType);
    }

    /**
     * 转换文件大小,指定转换的类型
     *
     * @param fileS    fileS
     * @param sizeType sizeType
     * @return
     */
    private static double FormatFileSize(long fileS, int sizeType) {
        DecimalFormat df = new DecimalFormat("#.00");
        double fileSizeLong = 0;
        switch (sizeType) {
            case SIZE_TYPE_B:
                fileSizeLong = Double.valueOf(df.format((double) fileS));
                break;
            case SIZE_TYPE_KB:
                fileSizeLong = Double.valueOf(df.format((double) fileS / 1024));
                break;
            case SIZE_TYPE_MB:
                fileSizeLong = Double.valueOf(df.format((double) fileS / 1048576));
                break;
            case SIZE_TYPE_GB:
                fileSizeLong = Double.valueOf(df.format((double) fileS / 1073741824));
                break;
            default:
                break;
        }
        return fileSizeLong;
    }

    /**
     * 获取指定文件大小
     *
     * @param file file
     * @return long
     * @throws IOException IOException
     */
    private static long getFileSize(File file) throws IOException {
        long size = 0;
        if (file.exists()) {
            FileInputStream fis = null;
            fis = new FileInputStream(file);
            size = fis.available();
        }
        return size;
    }

    /**
     * 获取指定文件夹
     *
     * @param f file
     * @return
     * @throws IOException IOException
     */
    private static long getFileSizes(File f) throws IOException {
        long size = 0;
        File flist[] = f.listFiles();
        for (int i = 0; i < flist.length; i++) {
            if (flist[i].isDirectory()) {
                size = size + getFileSizes(flist[i]);
            } else {
                size = size + getFileSize(flist[i]);
            }
        }
        return size;
    }

    /**
     * Try to return the absolute file path from the given Uri
     *
     * @param context context
     * @param uri     uri
     * @return the file path or null
     */
    public static String getRealFilePath(final Context context, final Uri uri) {
        if (null == uri) return null;
        String path = uri.toString();
        if (path.startsWith("content://" + getAuthority(context) + "/" + PROVIDER_PATH_NAME)) {
            return path.replace("content://" + getAuthority(context) + "/" + PROVIDER_PATH_NAME, Environment.getExternalStorageDirectory().getAbsolutePath());
        }
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    @Nullable
    public static InputStream getAssetsFileInputStream(Context context, String file) {
        try {
            return context.getAssets().open(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static final int DEFAULT_BUFFER_SIZE = 1024 * 1024 * 2;

    public static void copy(InputStream inputStream, OutputStream outputStream) {
        try {
            copyEnclosed(inputStream, outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            closeStreamAutoCatch(inputStream);
            closeStreamAutoCatch(outputStream);
        }
    }

    public static void copyEnclosed(InputStream inputStream, OutputStream outputStream) throws IOException {
        if (inputStream != null && outputStream != null) {
            byte[] buff = new byte[DEFAULT_BUFFER_SIZE];
            int len;
            while ((len = inputStream.read(buff)) != -1) {
                outputStream.write(buff, 0, len);
                outputStream.flush();
            }
        }
    }

    public static boolean decompressZip(InputStream inputStream, File dir) throws IOException {
        if (!dir.exists() && !dir.mkdirs()) {
            LogUtil.e(TAG,"fail to create dir: "+dir.getAbsolutePath());
            closeStreamAutoCatch(inputStream);
            return false;
        }
        if (!dir.isDirectory()) {
            LogUtil.e(TAG,"dir must be a directory: "+dir.getAbsolutePath());
            closeStreamAutoCatch(inputStream);
            return false;
        }
        ZipInputStream zipInputStream = new ZipInputStream(inputStream);
        for (ZipEntry entry = zipInputStream.getNextEntry(); entry != null; entry = zipInputStream.getNextEntry()) {
            Log.d(TAG, "decompressZip: "+entry.getName());
            File file = new File(dir, entry.getName());
            if (entry.isDirectory()) {
                file.mkdirs();
            } else {
                FileOutputStream outputStream = new FileOutputStream(file);
                BufferedOutputStream bos = new BufferedOutputStream(outputStream);
                copyEnclosed(zipInputStream,bos);
                closeStreamAutoCatch(bos);
            }
            zipInputStream.closeEntry();
        }
        closeStreamAutoCatch(zipInputStream);
        return true;
    }

    public static void copy(File file, File point) {
        if (!file.exists()) return;
        if (!point.getParentFile().exists()) point.getParentFile().mkdirs();
        BufferedInputStream inputStream = null;
        BufferedOutputStream outputStream = null;
        try {
            inputStream = getInputStream(file);
            outputStream = getOutputStream(point);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            copy(inputStream, outputStream);
        }
    }

    public static String getAuthority(Context context) {
        return context.getPackageName() + ".FileProvider";
    }

    @SuppressWarnings("ResultOfMethodCallIgnored")
    public static File getParentFile(String fileName) {
        File file = new File(Environment.getExternalStorageDirectory(), fileName);
        if (!file.exists()) file.mkdirs();
        return file;
    }

    /**
     * 删除指定目录下文件及目录
     *
     * @param deleteThisPath deleteThisPath
     * @param filePath       filepath
     */
    @SuppressWarnings("ResultOfMethodCallIgnored")
    public static void deleteFolderFile(String filePath, boolean deleteThisPath) {
        if (!TextUtils.isEmpty(filePath)) {
            try {
                File file = new File(filePath);
                if (file.isDirectory()) {// 如果下面还有文件
                    File files[] = file.listFiles();
                    for (int i = 0; i < files.length; i++) {
                        deleteFolderFile(files[i].getAbsolutePath(), true);
                    }
                }
                if (deleteThisPath) {
                    if (!file.isDirectory()) {// 如果是文件，删除
                        file.delete();
                    } else {// 目录
                        if (file.listFiles().length == 0) {// 目录下没有文件或者目录，删除
                            file.delete();
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void writeByteArrayToFile(File file, byte[] bytes) throws IOException {
        OutputStream outputStream = getOutputStream(file);
        outputStream.write(bytes);
        outputStream.flush();
        closeStream(outputStream);
    }

    public static BufferedInputStream getInputStreamAutoCatch(File file) {
        try {
            return getInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static BufferedInputStream getInputStream(File file) throws FileNotFoundException {
        return new BufferedInputStream(new FileInputStream(file));
    }

    public static BufferedOutputStream getOutputStreamAutoCatch(File file) {
        try {
            return getOutputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static BufferedOutputStream getOutputStream(File file) throws FileNotFoundException {
        return new BufferedOutputStream(new FileOutputStream(file));
    }

    public static void closeStreamAutoCatch(Closeable stream) {
        try {
            closeStream(stream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void closeStream(Closeable stream) throws IOException {
        if (stream == null) return;
        stream.close();
    }

    public static String getFileInString(File file) {
        if(file==null || !file.exists()){
            LogUtil.e(TAG,"can't find file...");
            return "";
        }
        StringBuilder builder=new StringBuilder();
        try {
            BufferedInputStream input = getInputStream(file);
            byte[] buffer=new byte[DEFAULT_BUFFER_SIZE];
            int length;
            while ((length=input.read(buffer))!=-1){
                builder.append(new String(buffer,0,length));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return builder.toString();
    }

    public static String randomFileName(String end) {
        return CommonUtils.md5Encrypt(System.currentTimeMillis()+"")+end;
    }
}
